#include <iostream>
#include <typeinfo>     // for typeid()
#include <assert.h>
#include <string>

class Any
{
private:
    struct holder
    {
    public:
        holder() = default;
        virtual ~holder() = default;
        virtual const std::type_info &type() = 0;
        virtual holder* clone() = 0;
    };
    //
    template<class T>
    struct placeholder : public holder
    {
    public:
        placeholder(const T& val) : _val(val) {};
        // virtual ~placeholder(){};                   // 不需要实现， T 的析构应由外部实现
        virtual const std::type_info &type() override { return typeid(T); }
        virtual holder* clone() override { return new placeholder(_val); }

    // private:
        T _val;
    };
private:
    // for slave
    Any &swap(Any &other) noexcept{
        std::swap(other._content, this->_content);
        return *this;
    }
 
private:
    holder *_content;

public:
    Any() : _content(nullptr) {}
    // 模板函数
    template<class T>
    Any(const T &val): _content(new placeholder(val)) {}
    Any(const Any &other): _content(other._content ? other._content->clone() : nullptr) {}
    ~Any() { delete _content; }

    // 返回所保存的数据的指针
    template<class T>
    T *get(){
        assert(_content->type() == typeid(T));
        return &(((placeholder<T>*)_content)->_val);
    }

    // operator=
    template<class T>
    Any& operator=(const T &val){
        Any(val).swap(*this);
        return *this;
    }

    Any& operator=(const Any &other){
        Any(other).swap(*this);
        return *this;
    }
};


struct Test{
public:
    Test(){
        std::cout << "构造" << std::endl;
    }
    ~Test(){
        std::cout << "析构" << std::endl;
    }
};

int main(){
    // test mem leak
    Any b;
    {
        Test test;
        b = test;
    }
    std::cout << "-----\n";

    Any a(5);
    a = 10;
    int *pa = a.get<int>();
    std::cout << *pa << std::endl;

    a = std::string("nihao");
    // a = "nihao";
    std::string *str = a.get<std::string>();
    std::cout << *str << std::endl;
    return 0;
}